#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 读写CSV数据
问题: 你想读写一个CSV格式的文件。
提示 : 
    1. tab分割的数据: f_tsv = csv.reader(f, delimiter='\t')
    2. 解决插入空行问题：newline=''
"""

import csv
from collections import namedtuple

stocks = 'stocks.csv'
stocks_w = '01_rw_csv.csv'

def recipe1():
    with open(stocks) as f:
        f_csv = csv.reader(f)
        headers = next(f_csv)
        print(f"{headers = }")
        for row in f_csv:
            print(f"{row = }")

def recipe2():
    '''使用命名元组'''
    with open(stocks) as f:
        f_csv = csv.reader(f)
        headings = next(f_csv)
        Row = namedtuple('Row', headings)
        for r in f_csv:
            row = Row(*r)
            print(f"{row = }")

def recipe3():
    '''字典序列'''
    with open(stocks) as f:
        f_csv = csv.DictReader(f)
        for row in f_csv:
            print(f"{row = }")

def recipe4():
    headers = ['Symbol','Price','Date','Time','Change','Volume']
    rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),
            ('AIG', 71.38, '6/11/2007', '9:37am', -0.15, 195500),
            ('AXP', 62.58, '6/11/2007', '9:38am', -0.46, 935000),
        ]
    with open(stocks_w, 'w', newline='') as f:
        f_csv = csv.writer(f)
        f_csv.writerow(headers)
        f_csv.writerows(rows)

def recipe5():
    headers = ['Symbol','Price','Date','Time','Change','Volume']
    rows = [{'Symbol':'AA', 'Price':39.48, 'Date':'6/11/2007',
            'Time':'9:36am', 'Change':-0.18, 'Volume':181800},
            {'Symbol':'AIG', 'Price': 71.38, 'Date':'6/11/2007',
            'Time':'9:37am', 'Change':-0.15, 'Volume': 195500},
            {'Symbol':'AXP', 'Price': 62.58, 'Date':'6/11/2007',
            'Time':'9:38am', 'Change':-0.46, 'Volume': 935000},
            ]
    with open(stocks_w, 'w', newline='') as f:
        f_csv = csv.DictWriter(f, headers)
        f_csv.writeheader()
        f_csv.writerows(rows)

def recipe6():
    '''类型转换'''
    col_types = [str, float, str, str, float, int]
    with open(stocks) as f:
        f_csv = csv.reader(f)
        headers = next(f_csv)
        print(f"{headers = }")
        for row in f_csv:
            row = tuple(convert(value) for convert, value in zip(col_types, row))
            print(f"{row = }")

def recipe7():
    '''转换字典中特定字段'''
    print('Reading as dicts with type conversion')
    field_types = [ ('Price', float),
                    ('Change', float),
                    ('Volume', int) ]
    with open(stocks) as f:
        for row in csv.DictReader(f):
            row.update((key, conversion(row[key])) for key, conversion in field_types)
            print(f"{row = }")

def main():
    print('recipe1'.center(20, '*'))
    recipe1() 
    print('recipe2'.center(20, '*'))
    recipe2() 
    print('recipe3'.center(20, '*'))
    recipe3() 
    print('recipe4'.center(20, '*'))
    recipe4() 
    print('recipe5'.center(20, '*'))
    recipe5() 
    print('recipe6'.center(20, '*'))
    recipe6() 
    print('recipe7'.center(20, '*'))
    recipe7() 

if __name__ == '__main__':
    main()               

